package com.micromall.common.sms;


import com.micromall.common.exception.BusiException;
import com.micromall.common.exception.ExceptionCode;
import com.micromall.common.utils.HttpHelper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by DanteFung on 2017/6/22.
 */
public class SmsMessageSender {

    /**饿汉式**/
    private static final SmsMessageSender smsMessageSender = new SmsMessageSender();

    public static SmsMessageSender getSingleton(){
        return smsMessageSender;
    }

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 发送手机短信
     * @param rcptMobiles 接收短信的手机
     * @param message 发送内容
     * @return
     * @throws Exception
     */
    public SmsSendResult sendSms(final String[] rcptMobiles, final String message) throws Exception {
        if (rcptMobiles.length > 100) {
            throw new BusiException(ExceptionCode.SMS_MORETHAN_100_PHONE.getDesc());
        }
        return this.sendSms(StringUtils.join(rcptMobiles, ","), message, "", "", "");
    }

    /**
     * 群发接口，可对手机群发相同内容的短信
     * @param dst 接收短信手机号，多个号码之间用英文逗号(,)隔开
     * @param msg 短信内容
     * @param time 定时时间(可不填)
     * @param subNo 子号码
     * @param txt 短信类型(可不填)，txt=ccdx表示启用超长短信功能
     * @return
     * @throws Exception
     */
    private SmsSendResult sendSms(String dst, String msg, String time, String subNo, String txt) throws Exception {
        String sUrl = null;
        String smsServer =  SmsConstant.smsParamMap.get("sms.139000.server.url");
        String smsName = SmsConstant.smsParamMap.get("sms.139000.name");
        String smsPassword = SmsConstant.smsParamMap.get("sms.139000.password");
        String smsEncoding = SmsConstant.smsParamMap.get("sms.encoding");
        try {
            sUrl = smsServer + "/send/gsend.asp?name=" + smsName + "&pwd=" + smsPassword + "&dst=" + dst + "&msg="
                    + URLEncoder.encode(msg, smsEncoding) + "&time=" + time + "&sender=" + subNo + "&txt=" + txt;
        } catch (UnsupportedEncodingException uee) {
            logger.error("短信URL编码错误.", uee);
        }

        // 返回值
        SmsSendResult smsSendResult = null;
        HttpHelper httpHelper = new HttpHelper.Builder(sUrl).build();
        String result = (String)httpHelper.doRequest();
        if (StringUtils.isNotBlank(result)) {
            result = result.replaceAll("\r", "").replaceAll("\n", "");
            smsSendResult = new SmsSendResult();
            String[] rs = result.split("&");
            for (String item : rs) {
                if (StringUtils.isEmpty(item))
                    continue;
                String[] items = item.split("=");
                if ("num".equals(items[0])) {
                    if (items.length > 1) {
                        smsSendResult.setSuccessCount(new Integer(items[1]));
                    } else {
                        smsSendResult.setSuccessCount(0);
                    }
                }
                if ("success".equals(items[0])) {
                    if (items.length > 1 && !StringUtils.isEmpty(items[1])) {
                        smsSendResult.setSuccessMobiles(StringUtils.split(items[1], ","));
                    }
                }
                if ("faile".equals(items[0])) {
                    if (items.length > 1 && !StringUtils.isEmpty(items[1])) {
                        smsSendResult.setFaileMobiles(StringUtils.split(items[1], ","));
                    }
                }
                if ("err".equals(items[0])) {
                    if (items.length > 1) {
                        smsSendResult.setReturnMsg(items[1]);
                    }
                }
                if ("errid".equals(items[0])) {
                    if (items.length > 1) {
                        smsSendResult.setErrorId(new Integer(items[1]));
                    }
                }
            }
        }
        return smsSendResult;
    }
}
